import React, { useState, useRef, useEffect } from 'react'

export default function SuperPasswordInput({ label, value, handleChange, state, autoComplete }) {
  const [inputValue, setInputValue] = useState(value || '');
  const [show, setShow] = useState(false);
  const inputRef = useRef(null);

  useEffect(() => {
    setInputValue(value || '');
  }, [value]);

  const onChange = () => {
    setInputValue(inputRef.current.value);
    handleChange(inputRef.current.value);
  };

  return (
    <div className="flex flex-col gap-0.5 my-4">
      {label && <label className="form-label text-sm text-gray-600">{label}：</label>}
      {state ? (
        <div className="relative w-1/2">
          <input ref={inputRef} type={show ? 'text' : 'password'} className="form-control rounded-xs text-base text-gray-800 px-3 py-2 border border-gray-400 focus:outline-none focus:border-gray-400 focus:ring-1 focus:ring-gray-400 w-full pr-10" value={inputValue} onChange={onChange} autoComplete={autoComplete} />
          <button type="button" className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 focus:outline-none" tabIndex={-1} onClick={() => setShow(s => !s)} aria-label={show ? '隐藏密码' : '显示密码'} >
            {show ? (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /> </svg>
            ) : (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.477 0-8.268-2.943-9.542-7a9.956 9.956 0 012.293-3.95M6.873 6.872A9.956 9.956 0 0112 5c4.477 0 8.268 2.943 9.542 7a9.956 9.956 0 01-4.043 5.306M15 12a3 3 0 11-6 0 3 3 0 016 0z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3l18 18" /> </svg>
            )}
          </button>
        </div>
      ) : (
        <div className="text-base text-gray-800 px-3 py-2 border border-gray-300 rounded-xs w-1/2 select-all min-h-[40px]">
          {inputValue ? '******' : ''}
        </div>
      )}
    </div>
  )
}